<?php
/**
 * Created by PhpStorm.
 * User: tomas
 * Date: 16/6/7
 * Time: 下午4:23
 */

namespace common\traits;


use mybackend\models\MyAdminIdentity;
use Yii;
use yii\helpers\Json;
use common\entities\KfsDbEntity;

trait LogActionTrait
{
    /**
     * @param \yii\base\Action $action
     */
    public function logAction($action)
    {
        try {
            $user = '';
            $orgCode = '';
            $userguid = 'GUEST';
            if (Yii::$app->user->getIsGuest()) {
                $user = "GUEST";
            } else {
                /** @var MyAdminIdentity $userInfo */
                $userInfo = Yii::$app->user->identity;
                $userguid = $userInfo->userguid;
                $user = $userInfo->usercode;
            }

            $projectId = $this->_getProjectId();

            $logData = [
                'time' => date("Y-m-d H:i:s"),
                'timestamp' => time(),
                'appId' => Yii::$app->id,
                'hostIp' => $this->_getHostIp(),
                'clientIp' => $this->getClientIP(),
                'orgCode' => $orgCode,
                'token' => Yii::$app->request->request('token',''),
                'projectId' => $projectId,
                'userId' => $userguid,
                'action' => $action->getUniqueId(),
                'get' => Yii::$app->request->get(),
                'post' => Yii::$app->request->post(),
            ];

            $this->maskLogPassword($logData);
            Yii::info(Json::encode($logData), "operate");
        }catch(\Exception $e){
            Yii::error("记录ActionLog出错" . (string)$e);
        }
    }

    /**
     * 获取客户端IP地址
     * @return string
     */
    public function getClientIP()
    {
        $ip = getenv("HTTP_X_FORWARDED_FOR");
        if(!$ip){
            $ip = $_SERVER["REMOTE_ADDR"];
        }
        return $ip;
    }

    /**
     * 获取服务器IP
     * @return string
     */
    private function _getHostIp()
    {
        $hostIp = getenv('HOST_IP');
        if (!$hostIp) {
            $hostIp = $_SERVER['SERVER_ADDR'];
        }
        return $hostIp;
    }

    /**
     * 获取项目ID
     * @return array|string
     */
    private function _getProjectId()
    {
        //搜索代码，有以下传入项目ID的情况，满足一种则返回
        $projIdList = ['proj_id', 'projectId', 'projIds', 'proj_ids', 'projectids', 'projId'];
        foreach ($projIdList as $proj_id) {
            if (Yii::$app->request->request($proj_id, '')) {
                return Yii::$app->request->request($proj_id);
            }
        }
        return '';
    }

    protected function maskLogPassword(array &$logData)
    {
        $passwordField = ['password', 'pwd'];
        foreach ($passwordField as $field) {
            if (isset($logData['get'][$field]) && is_string($logData['get'][$field])) {
                $logData['get'][$field] = str_repeat('*', strlen($logData['get'][$field]));
            }
            if (isset($logData['post'][$field]) && is_string($logData['post'][$field])) {
                $logData['post'][$field] = str_repeat('*', strlen($logData['post'][$field]));
            }
        }
    }
}